﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class ResultController : BaseController {

	public UISprite grid;
	public UIScrollView scrollView;
	public UIScrollBar scrollBar;
	private float width;


	void Start () {
		NotificationCenter.Get().AddEventListener(API.GAME_LOGS, ShowLog);

		width = Utils.GetScreenWidth() - 300;
		API.GetGameLog ();

//		for (int i = 0; i < grid.transform.childCount; i++) {
//			NGUITools.Destroy (grid.transform.GetChild (i));
//		}
	}
	void OnDestroy(){
		NotificationCenter.Get().RemoveEventListener(API.GAME_LOGS,ShowLog);
	}

	void Update(){
		base.Update ();
		width = Math.Abs(scrollView.bounds.min.x - scrollView.bounds.max.x);
	}
		
	void ShowLog(object obj){
//		for (int i = 0; i < grid.transform.childCount; i++) {
//			NGUITools.Destroy (grid.transform.GetChild (i).gameObject);
//		}
		if(grid.transform.childCount > 0){
			return;
		}

		JSONObject json = new JSONObject (obj.ToString());
		UIGrid gridCompent = grid.GetComponent<UIGrid>();
		gridCompent.cellWidth = width;
		int totalItem = 0;

		for (int i = 0; i < json ["list"].list.Count; i++) {

			JSONObject record = json["list"].list[i];

			if (record ["flows"] == null)
				continue;

			//获取人数
			List<JSONObject> players = GetPlayer(record);
			GameObject item = NGUITools.AddChild(grid.gameObject, getItem(players.Count));

			//iteam重新排列
			for(int j=0;j<players.Count;j++){
				UILabel nameLabel = GetGameObjectByName<UILabel> (item, "Player" + (j + 1));
				UILabel scoreLabel = GetGameObjectByName<UILabel> (item, "Score" + (j + 1));
				nameLabel.width = int.Parse((width / 4f).ToString());
				scoreLabel.width = int.Parse((width / 4f).ToString());
				if (nameLabel == null || scrollBar == null) {
					continue;
				}
				float n = (players.Count <= 4 ? 4 : players.Count);
				float x = j *(width/n) - (width/2) + (width / 2 / n);
				nameLabel.transform.position = new Vector3 (x / 360, nameLabel.transform.position.y, 0);
				scoreLabel.transform.position = new Vector3 (x / 360, scoreLabel.transform.position.y, 0);
			}

			string key = "FLOW|"+record ["hash_id"].str.Split ('|') [1] + '|';
			int index = 0;
			while(record ["flows"] [key + index.ToString ()] != null){
				JSONObject dataJson = new JSONObject(record ["flows"] [key + index.ToString ()]["data_json"].str.Replace("\\",""));

				//序号
				UILabel idx = GetGameObjectByName<UILabel> (item, "Index");
				idx.text = (i + 1).ToString();
				//房间号
				UILabel room = GetGameObjectByName<UILabel> (item, "ID");
				room.text = "房间号：" + record ["id"].str;
				//日期
				UILabel time = GetGameObjectByName<UILabel> (item, "Time");
				System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
				DateTime dt = startTime.AddSeconds(ChangeDataToD(record ["flows"] [key + index.ToString ()] ["create_time"].ToString()));
//				DateTime dt = new DateTime (ChangeDataToD(record ["flows"] [key + index.ToString ()] ["create_time"].ToString()));
				time.text = "开始时间：" + dt.ToString ("yyyy-MM-dd HH:mm:ss");

				//遍历详细记录
				for (int j = 0; j < dataJson.list.Count; j++) {
					JSONObject data = dataJson [j];
					//id
					string id = data ["player_id"].str;
					//用户信息
					JSONObject info = GetPlayerInfo (players, id);
//					结果信息
					SetPlayer (item,j,info,data);
				}

				index++;
				totalItem++;
			}

			item.name = "gridItem" + i;
			item.GetComponent<UIDragScrollView> ().scrollView = scrollView;


			UIWidget rt = item.GetComponent<UIWidget>();
			rt.width = (int)width;

			scrollBar.value = 0.1f;
		}
//		Debug.Log (gridCompent.cellWidth);
//		Debug.Log (width);
		gridCompent.repositionNow = true;
		scrollView.ResetPosition ();
	}

	private void SetPlayer(GameObject item,int idx,JSONObject player,JSONObject data){
		UILabel username = GetGameObjectByName<UILabel> (item, "Player" + (idx + 1));
		username.text = player ["info"]["username"].str;
		UILabel score = GetGameObjectByName<UILabel> (item, "Score" + (idx + 1));
		score.text = data ["total"].ToString();
		username.gameObject.SetActive (true);
		score.gameObject.SetActive (true);
	}

	private GameObject getItem(int playerNum){
		if(playerNum < 5){
			return (GameObject)(Resources.Load("Result Item1"));
		}
		if(playerNum == 5){
			return (GameObject)(Resources.Load("Result Item2"));
		}
		return (GameObject)(Resources.Load("Result Item3"));
	}

	//获取房间有效成员
	private List<JSONObject> GetPlayer(JSONObject json){
		List<JSONObject> results = new List<JSONObject>();
		JSONObject players = new JSONObject (json ["players_json"].str.Replace ("\\", ""));
		foreach (var p in players.list) {
			results.Add (p);
		}
		return results;
	}

	//获取指定id的人
	private JSONObject GetPlayerInfo(List<JSONObject> playerList,string id){
		foreach (var p in playerList) {
			if (p ["id"].str == id)
				return p;
		}
		Debug.Log ("没有找到用户");
		return null;
	}

	private T GetGameObjectByName<T>(GameObject gameObject,string name){
		GameObject obj = findChild (gameObject, name);
		if (obj != null) {
			return obj.GetComponent <T> ();
		}
		return default(T);
	}

	private GameObject findChild(GameObject parent,string name){
		for (int i = 0; i < parent.transform.childCount; i++) {
			GameObject obj = parent.transform.GetChild(i).gameObject;
			if (obj.name.Equals (name)) {
				return obj;
			}else if (obj.transform.childCount > 0) {
				GameObject child = findChild (obj, name);
				if (child != null) {
					return child;
				}
			}
		}
		return null;
	}

	private long ChangeDataToD(string strData)
	{
		Decimal dData = 0.0M;
		if (strData.Contains("E"))
		{
			dData = Convert.ToDecimal(Decimal.Parse(strData.ToString(), System.Globalization.NumberStyles.Float));
		}
		long time = long.Parse (dData.ToString ()) / 1000;
		Debug.Log (time);
		return time;
	}


	public void exit(){
		EffectUtil.DianJi();
		SceneManager.LoadScene ("Home");
	}
}
